﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Collections;
using System.Data;
using System.IO;

public partial class tools_DBManage : System.Web.UI.Page
{
    private string BackFolder = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        BackFolder = Server.MapPath("~/upload/");

        Response.Write(DateTime.Now.ToString("yyyyMMddhhmmssfffffff"));

        if (!IsPostBack)
        {
            GridView1_Bind();
        }
    }

    private void GridView1_Bind()
    {
        if (string.IsNullOrEmpty(BackFolder)) { return; }
        string Folder = BackFolder;

        string[] fileList = Directory.GetFiles(Folder);

        DataTable dt = new DataTable();
        dt.Columns.Add("fileName", typeof(string));
        foreach (string s in fileList)
        {
            DataRow dr = dt.NewRow();
            dr["fileName"] = s;
            dt.Rows.Add(dr);
        }

        GridView1.DataSource = dt;
        GridView1.DataBind();
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        DAL(false, "");
        GridView1_Bind();
    }

    private void RestoreDBKill()
    {
        using (SqlConnection conn = new SqlConnection(@"Data Source=PETERZHU\PETERSQL2008;Integrated Security=True"))
        {
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
            //杀死所有正在使用要还原数据的数据库进程
            SqlCommand cmd = new SqlCommand("SELECT spid FROM sysprocesses ,sysdatabases WHERE sysprocesses.dbid=sysdatabases.dbid AND sysdatabases.Name='testdb'", conn);
            SqlDataReader dr;

            dr = cmd.ExecuteReader();
            ArrayList list = new ArrayList();
            while (dr.Read())
            {
                list.Add(dr.GetInt16(0));
            }
            dr.Close();
            for (int k = 0; k < list.Count; k++)
            {
                cmd = new SqlCommand(string.Format("KILL {0}", list[k]), conn);
                cmd.ExecuteNonQuery();
            }
        }
    }

    private void DAL(bool isstore, string restoreFile)
    {
        string restore = "use master; restore database testdb from disk='" + restoreFile + "' WITH REPLACE;";

        string backFile = BackFolder + string.Format("testdb_{0}.bak", DateTime.Now.ToString("yyyyMMddhhmmssfffffff"));
        string backupstr = "use master; backup database testdb to disk='" + backFile + "';";

        string strSql = "";

        if (isstore)
        {
            strSql = restore;
            RestoreDBKill();
        }
        else { strSql = backupstr; }

        SqlConnection con = new SqlConnection(@"Data Source=PETERZHU\PETERSQL2008;Integrated Security=True");
        SqlCommand cmd = new SqlCommand(strSql, con);
        try
        {
            con.Open();
            cmd.ExecuteNonQuery();
        }
        catch (SqlException ex)
        {
            ErrorMsg.Text = ex.ToString();
        }
        finally
        {
            con.Close();
        }
    }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "restore")
        {
            string file = e.CommandArgument.ToString();

            DAL(true, file);

        }
        GridView1_Bind();
    }

    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string file = (string)e.Keys[0];
        if (File.Exists(file))
        {
            File.Delete(file);
        }
        GridView1_Bind();
    }
}